﻿using System.Web.Mvc;

namespace Nb.Common.Web.Mvc
{
    /// <summary>
    /// 自定义的ThemeViewEngine只对View和Partial View有效，对于MasterPage无效
    /// 所以自己实现其查找机制
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
    {
        private string _themeableLayout = null;
        public override string Layout
        {
            get
            {
                //null不做任何处理
                if (string.IsNullOrWhiteSpace(base.Layout))
                {
                    return base.Layout;
                }
                
                //避免多次计算
                if (!string.IsNullOrEmpty(_themeableLayout))
                {
                    return _themeableLayout;
                }

                _themeableLayout = ThemeableMasterPageViewLocationFinder.FindLayoutViewPath(base.Layout, ViewContext);
                return _themeableLayout;
            }
            set
            {
                base.Layout = value;
            }
        }

        #region nested class

        internal class ThemeableMasterPageViewLocationFinder
        {
            /// <summary>
            /// 自定义的ThemeViewEngine只对View和Partial View有效，对于MasterPage无效，所以调用自己的实现
            /// 手动调用ViewEngines的查找方法，如FindPartialView或FindView
            /// </summary>
            /// <param name="layoutPath"></param>
            /// <param name="viewContext"></param>
            /// <returns></returns>
            public static string FindLayoutViewPath(string layoutPath, ViewContext viewContext)
            {
                string themeableLayoutPath = null;
                var layoutNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(layoutPath);
                ViewEngineResult layoutViewResult = ViewEngines.Engines.FindPartialView(viewContext.Controller.ControllerContext, layoutNameWithoutExtension);
                //ViewEngineResult layoutViewResult = ViewEngines.Engines.FindView(viewContext.Controller.ControllerContext, layoutNameWithoutExtension, "");
                if (layoutViewResult != null && layoutViewResult.View is RazorView)
                {
                    themeableLayoutPath = (layoutViewResult.View as RazorView).ViewPath;
                }

                return themeableLayoutPath;
            }
        }

        #endregion
    }

    public abstract class WebViewPage : WebViewPage<dynamic>
    {
    }
}